//
//  WorkflowSelectUserViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 2017/8/30.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "WorkflowSelectUserViewController.h"
#import "WorkflowSelectUserCell.h"
#import "CommnetMessageSendPanel.h"
#import "WorkflowMenuListViewController.h"

NSString *const WorkflowSelectUserViewControllerFormDicParametersParamKey = @"WorkflowSelectUserViewControllerFormDicParametersParamKey";
NSString *const WorkflowSelectUserViewControllerOptTypeParametersParamKey =
    @"WorkflowSelectUserViewControllerOptTypeParametersParamKey";

@interface WorkflowSelectUserViewController ()<CommnetMessageSendPanelDelegate>
{
    NSMutableDictionary *_formDic;
    NSMutableDictionary *_submitDic;
    WorkflowSelectUserInfo *_selectUserInfo;
    
    NSMutableArray *_netData;
    RSWDataOperation *_manager;
    
    CommnetMessageSendPanel *_sendPanel;
    MultiFoldInfo *_selectedFoldCellModel;
    
    WorkflowOptType _workflowOptType;
    Boolean _isEndWorkflow;
    
    NSArray *_attachment;
}
@end

@implementation WorkflowSelectUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    [self checkSession];
    
    _formDic = self.param[WorkflowSelectUserViewControllerFormDicParametersParamKey];
    _attachment = _formDic[@"attachment"];
    [_formDic removeObjectForKey:@"attachment"];
    
    _workflowOptType = [self.param[WorkflowSelectUserViewControllerOptTypeParametersParamKey] integerValue];
    
    [self setBackNavigateItemTitle:@"工作人员列表"];
    
    [self initVariable];
    [self initUI];
    
    [_manager getStepRoleUserTree:_formDic[@"Conditions"][@"Slickflow_ProcessCode"]
                            version:_formDic[@"Conditions"][@"Slickflow_Version"]
                                dic:_formDic
                                workflowOptType:_workflowOptType
                         completion:^(NSInteger nResult, id output, NSError *error) {
                             [self requestComplete:nil result:nResult output:output error:error];
                         }];
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    
    [_manager terminateRequest];
    
    [self removeObserver];
}

-(void)initVariable
{
    _submitDic = [NSMutableDictionary new];
    _netData = [NSMutableArray new];
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    [self addKeyboardObserver];
}

- (void)initUI
{
    [super createTableView:XUITabelViewStyleTypePlain];
    _ctable.separatorExistFollowCell = YES;
}

-(void)reloadView
{
    self.data = [NSMutableArray new];
    for (int i = 0; i < _netData.count; i++) {
        MultiFoldInfo *foldCellModel = [MultiFoldInfo modelWithDic:(NSDictionary *)_netData[i]];
        [self.data addObject:foldCellModel];
    }
    
    [_ctable reloadData];
}

-(void)requestComplete:(XMSDataOperationManager *)dom result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
     {
         switch(requestResult)
         {
             case YES:
             {
                 _selectUserInfo = output;
                 
                 NSMutableArray *arFirst = [NSMutableArray new];
                 [_netData addObject:@{
                                       @"pid":@"",
                                       @"pkid":@"root",
                                       @"text":_selectUserInfo.message,
                                       @"level":@"0",
                                       @"submodels":arFirst,
                                       }];
                 for (NSInteger i = 0; i < _selectUserInfo.entity.count; i ++)
                 {
                     WorkflowUserEntityInfo *entity = _selectUserInfo.entity[i];
                     NSMutableArray *arSecond = [NSMutableArray new];
                     NSDictionary *dic = @{
                                           @"pid":@"root",
                                           @"pkid":entity.activityGUID,
                                           @"text":entity.activityName,
                                           @"level":@"1",
                                           @"submodels":arSecond,
                                           };
                     [arFirst addObject:dic];
                     
                     for (NSInteger j = 0; j < entity.participants.count; j ++)
                     {
                         WorkflowParticipantInfo *participant = entity.participants[j];
                         NSMutableArray *arThird = [NSMutableArray new];
                         NSDictionary *dic = @{
                                               @"pid":entity.activityGUID,
                                               @"pkid":participant.typeId,
                                               @"text":participant.name,
                                               @"level":@"2",
                                               @"submodels":arThird,
                                               };
                         [arSecond addObject:dic];
                         
                         for (NSInteger k = 0; k < participant.users.count; k ++)
                         {
                             WorkflowUserInfo *user = participant.users[k];
                             NSDictionary *dic = @{
                                                   @"pid":entity.activityGUID,
                                                   @"pkid":user.userID,
                                                   @"text":user.userName,
                                                   @"level":@"3",
                                                   };
                             [arThird addObject:dic];
                         }
                     }
                 }
                 
                 [self reloadView];
                 
                 break;
             }
             default:
             {
                 break;
             }
         }
     }];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MultiFoldInfo *foldCellModel = self.data[indexPath.row];

    if(foldCellModel.level.intValue == 3)
        return 80;
    
    return [WorkflowSelectUserCell caleHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MultiFoldInfo *foldCellModel = self.data[indexPath.row];
    
    static NSString *identifier = @"identifier";
    WorkflowSelectUserCell *cell = [[WorkflowSelectUserCell alloc] initWithReuseIdentifier:identifier];
    
    cell.title = foldCellModel.text;
    [cell setTitleLeftLevel:foldCellModel.level.intValue];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MultiFoldInfo *didSelectFoldCellModel = self.data[indexPath.row];
    
    if([self canSendNext:didSelectFoldCellModel])
    {
        if(_sendPanel == nil)
        {
            _sendPanel = [[CommnetMessageSendPanel alloc]initWithFrame:CGRectMake(0, self.view.height, self.view.width, 44)];
            _sendPanel.textView.placeholder = @"备注";
            _sendPanel.delegate = self;
            [self.view addSubview:_sendPanel];
        }
        
        _selectedFoldCellModel = didSelectFoldCellModel;
        [_sendPanel becomeFirstResponder];
        return;
    }
    else
    {
         [_sendPanel resignFirstResponder];
    }
    
    WorkflowSelectUserCell *cell = [tableView cellForRowAtIndexPath: indexPath];
    
    [tableView beginUpdates];
    if (didSelectFoldCellModel.belowCount == 0) {
        cell.arrowImage = @"img_arrowdown";
        
        //Data
        NSArray *submodels = [didSelectFoldCellModel open];
        NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:((NSRange){indexPath.row + 1,submodels.count})];
        [self.data insertObjects:submodels atIndexes:indexes];
        
        //Rows
        NSMutableArray *indexPaths = [NSMutableArray new];
        for (int i = 0; i < submodels.count; i++) {
            NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
            [indexPaths addObject:insertIndexPath];
        }
        [tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        
    }else {
        cell.arrowImage = @"img_arrowup";
        
        //Data
        NSArray *submodels = [self.data subarrayWithRange:((NSRange){indexPath.row + 1,didSelectFoldCellModel.belowCount})];
        [didSelectFoldCellModel closeWithSubmodels:submodels];
        [self.data removeObjectsInArray:submodels];
        
        //Rows
        NSMutableArray *indexPaths = [NSMutableArray new];
        for (int i = 0; i < submodels.count; i++) {
            NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
            [indexPaths addObject:insertIndexPath];
        }
        [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    }
    [tableView endUpdates];
}

-(Boolean)canSendNext:(MultiFoldInfo*)foldInfo
{
    Boolean falg = NO;
    _isEndWorkflow = NO;
    
    if(foldInfo.level.intValue == 3)
    {
        falg = YES;
    }
    else if([self isFinishFlag:foldInfo] == YES)
    {
        falg = YES;
        _isEndWorkflow = YES;
    }
    
    return falg;
}

-(Boolean)isFinishFlag:(MultiFoldInfo*)foldInfo
{
    Boolean falg = NO;
    if(foldInfo.level.intValue == 1 && [foldInfo.text isEqualToString:WfFinishFlag])
    {
        falg = YES;
    }
    
    return falg;
}

#pragma mark --
#pragma mark -- send reply

- (void)commnetMessageSendPanelSendText:(CommnetMessageSendPanel *)panel
{
    if(_sendPanel.textView.text.length <=0 || [_sendPanel.textView.text isBlankString] )
    {
        [UIAlertView showInfoMsg:[NSString stringWithFormat:@"请输入备注"]];
        return;
    }
    
    [_sendPanel resignFirstResponder];
    
    [_submitDic setValue:[[_formDic valueForKey:@"Conditions"] mutableCopy] forKey:@"Model"];
    
    NSDictionary *dic = @{_selectedFoldCellModel.pId:@[@{
                                                                @"UserID":_selectedFoldCellModel.pkId,
                                                                @"UserName":_selectedFoldCellModel.text
                                                                }]};
    if(_isEndWorkflow == YES)
    {
        dic = @{_selectedFoldCellModel.pkId:@[]};
    }
    [_formDic setValue:dic forKey:@"NextActivityPerformers"];
    
    //去掉attachment
    [[_formDic valueForKey:@"Conditions"] removeObjectForKey:@"attachment"];
    [_submitDic setValue:_formDic forKey:@"WfAppRunner"];
    [_submitDic setValue:_sendPanel.textView.text forKey:@"Comment"];
    [_submitDic setValue:_formDic[@"attachment"] forKey:@"attachment"];
    
    if(_workflowOptType == WorkflowOptTypeApply)
    {
        [self startWorkflow];
    }
    else
    {
        [self nextWorkflow];
    }
}

-(void)startWorkflow
{
    [_manager startWorkflowAppInstance:_formDic[@"Conditions"][@"Slickflow_ProcessCode"]
                               version:_formDic[@"Conditions"][@"Slickflow_Version"]
                                   dic:[_submitDic mutableCopy] 
                            completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"提交成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                               [[XUINavigationController navigationController] popToRootViewControllerAnimated:YES];
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"提交失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"提交失败"];
                      break;
                  }
              }
          }];
     }];
}

-(void)nextWorkflow
{
    [_manager nextWorkflowAppInstance:_formDic[@"Conditions"][@"Slickflow_ProcessCode"]
                              version:_formDic[@"Conditions"][@"Slickflow_Version"]
                                  dic:[_submitDic mutableCopy]
                           attachment:_attachment
                           completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"提交成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                               if([XUINavigationController containViewControllers:@[@"WorkflowListViewController"]].count > 0)
                               {
                                   [XUINavigationController popToViewControllerClass:NSClassFromString(@"WorkflowListViewController")];
                               }
                               if([XUINavigationController containViewControllers:@[@"WorkflowToDoListViewController"]].count > 0)
                               {
                                   [XUINavigationController popToViewControllerClass:NSClassFromString(@"WorkflowToDoListViewController")];
                               }
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"提交失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"提交失败"];
                      break;
                  }
              }
          }];
     }];
}

#pragma mark --
#pragma mark -- keyBoard observer

- (BOOL)keyboardWillShow:(NSNotification *)noti
{
    BOOL bResult = [super keyboardWillShow:noti];
    if (YES == bResult)
    {
        double duration = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        NSInteger curve = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
        [UIView animateWithDuration:duration delay:0 options:curve animations:^
         {
             _sendPanel.bottom = self.view.height - self.keyboardOffSet;
             
         } completion:^(BOOL finished)
         {
         }];
    }
    return bResult;
}

- (BOOL)keyboardWillHide:(NSNotification *)noti
{
    BOOL bResult = [super keyboardWillHide:noti];
    if(YES == bResult)
    {
        double duration = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        NSInteger curve = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
        [UIView animateWithDuration:duration delay:0 options:curve animations:^
         {
             _sendPanel.top = self.view.height;
             
         }completion:^(BOOL finished)
         {
         }];
    }
    return bResult;
}

- (void)keyboardWillChangeSize:(CGFloat)changeSize withAnimationDuration:(CGFloat)duration curve:(UIViewAnimationCurve)curve
{
    [UIView animateWithDuration:0.25 animations:^
     {
         _sendPanel.top += changeSize;
     }];
}

#pragma mark --
#pragma mark -- scroll delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_sendPanel resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
